import re

from django.contrib.auth.backends import ModelBackend

from user.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """自定义jwt认证成功返回数据"""
    return {
        'token': token,
        'user_id': user.id,
        'user_name': user.username,
    }


class MyModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        根据账号获取user对象
        :param account: 账号=>手机号或用户名
        :return: user对象 或 None
        """
        try:
            # 判断用户名是手机号还是密码
            if re.match(r'^1[1-9]\d{9}$', username):
                user = User.objects.get(mobile = username)
            else:
                user = User.objects.get(username = username)
        except User.DoesNotExist:
            return None
        # 验证密码
        if user.check_password(password):
            return user
        else:
            return None
